package org.microservice.common.handler;

import lombok.extern.slf4j.Slf4j;
import org.microservice.common.util.CustomRuntimeException;
import org.microservice.common.util.R;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * Created with IntelliJ IDEA.
 * User: 齐丹枫
 * Date: 2018/6/22
 * Time: 11:09
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Slf4j
@RestControllerAdvice
public class CustomExceptionHandler {


    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity handleNoHandlerFoundException(Exception e){
        log.error(e.toString());
        return generateResponseEntity(R.error(404,"接口不存在"),404);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity handleAccessDeniedException(Exception e){
        log.error(e.toString());
        return generateResponseEntity(R.error(401,"认证失败"),500);
    }


    @ExceptionHandler(CustomRuntimeException.class)
    public ResponseEntity handleCustomRuntimeException(Exception e){
        log.error(e.toString());
        return generateResponseEntity(R.error(e.getMessage()),500);
    }


    @ExceptionHandler(Exception.class)
    public ResponseEntity handleException(Exception e){
        log.error(e.toString());
        return generateResponseEntity(R.error(),500);

    }



    private ResponseEntity generateResponseEntity(R r,int code){
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        ResponseEntity<R> response = new ResponseEntity<R>(r, headers,
                HttpStatus.valueOf(code));
        return  response;
    }
}
